<template>
  <div>
      <div class="top" v-if="store_data.name">
          <div class="shop_img">
                <img :src="store_data.logo" alt="">
            </div>
          <h3>{{store_data.name}}</h3>
      </div>
      <div class="wrapper" v-if="store_coupon">
            <div class="item" v-if="store_coupon.type == '1'">
                <div class="lst_left">
                    <div>
                        <h4 class="coupon_name">{{store_coupon.name}}</h4>
                        <p v-if="store_coupon.full_price != '0'" class="coupon_info">折扣劵 <em>满{{store_coupon.full_price}}元可用</em> </p>
                        <p v-else class="coupon_info">通用优惠券</p>
                        <p class="coupon_date" v-if="store_coupon.end_time !='-1'">{{store_coupon.start_time*1000 | formatDate}}-{{store_coupon.end_time*1000 | formatDate}}</p>
                        <p class="coupon_date" v-else>使用期限：无期限</p>
                    </div>
                </div>
                <div class="lst_right">
                    <div class="xiantiao_icon" :style="xiantiao_icon">
                    </div>
                    <div>
                        <p class="coupon_price"> <em></em> {{store_coupon.ratio}}折</p>
                        <a href="javascript:;"  class="coupon_btn" :style="coupon_btn" @click="receiveCoupon(store_coupon.id,store_coupon.store_id)">立即领取</a>
                    </div>
                </div>
            </div>
            <div class="item" v-if="store_coupon.type == '2'">
                <div class="lst_left">
                    <div>
                        <h4 class="coupon_name">{{store_coupon.name}}</h4>
                        <p v-if="store_coupon.full_price != '0'" class="coupon_info">满减劵 <em>满{{store_coupon.full_price}}元可用</em> </p>
                        <p v-else class="coupon_info">通用优惠券 </p>
                        <p class="coupon_date" v-if="store_coupon.end_time !='-1'">{{store_coupon.start_time*1000 | formatDate}}-{{store_coupon.end_time*1000 | formatDate}}</p>
                        <p class="coupon_date" v-else>使用期限：无期限</p>
                    </div>
                </div>
                <div class="lst_right">
                    <div class="xiantiao_icon" :style="xiantiao_icon">
                    </div>
                    <div>
                        <p class="coupon_price"> <em>&yen;</em> {{store_coupon.price}}</p>
                        <a href="javascript:;"  class="coupon_btn" :style="coupon_btn" @click="receiveCoupon(store_coupon.id,store_coupon.store_id)">立即领取</a>
                    </div>
                </div>
            </div>
        </div>
        <div>
            <div class="shop_list_box border-bottom-1px"  v-for="(item,i) in store_list" :key="i">
                <div class="shop_list_item">
                    <router-link class="left_fl" tag="div" :to="{ name:'ShopDetails',query:{store_id:item.id,type:'itemFollow'}}">
                        <img :src="item.logo" alt="">
                    </router-link>
                    <div class="right_fl">
                        <div class="right_info">
                            <router-link tag="div" class="right_info_top" :to="{ name:'ShopDetails',query:{store_id:item.id,type:'itemFollow'}}">
                                <h3 class="shop_name">{{item.name}}</h3>
                                <span>{{item.juli}}km</span>
                            </router-link>
                            <p class="shop_info">
                                {{item.address || ""}}
                            </p>
                            <p v-if="item.kf_mobile" class="shop_info">电话：{{item.kf_mobile}}</p>
                            <div class="coupon_list coupon_txt"
                            v-for="(coupon_list,index) in item.coupon_list"
                            @click="receiveCoupon(item.id,coupon_list.id)">
                                <div class="coupon_list_left">
                                    <div class="coupon_list_bg" :style="coupon_list_bg">
                                        <p><i class="coupon_icon" :style="coupon_icon"></i>
                                        {{coupon_list.name}}</p>
                                    </div>
                                </div>
                                <div class="coupon_list_right" :class="coupon_list.isActive ? 'coupon_action':'coupon_none'">
                                    立即领取
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
  </div>
</template>
<script>
import wx from 'weixin-js-sdk';
import {formatDate} from '@/util/date.js';
export default {
    filters: {
        formatDate(time) {
            var date = new Date(time);
            return formatDate(date, 'yyyy-MM-dd hh:mm');
        }
    },
    metaInfo: {
      title: "领取优惠券"
    },
    data(){
        return{
            xiantiao_icon:{
                backgroundImage: "url(" + require("../assets/coupon-xuxian@2.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            coupon_btn:{
                backgroundImage: "url(" + require("../assets/page3_btn_coupon@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            coupon_icon:{
                backgroundImage: "url(" + require("../assets/coupon_icon1@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            coupon_list_bg:{
                backgroundImage: "url(" + require("../assets/coupon_list_bg@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            store_data:{},
          store_list:[],
          store_coupon:{}

        }
    },
    methods:{
        //店铺列表
        get_store_list(latitude,longitude){
            let that = this;
            let store_id = that.$route.query.store_id;
            if(!latitude && !longitude){
                latitude = "22.7232188244294";
                longitude = "114.26097540916496";
            }
            that.$axios.post("/fang/store/pay_store", this.$qs.stringify({
                        lat:latitude,
                        lng:longitude,
                        store_id:store_id
                    })
                )
                .then(function (response) {
                    console.log(response);
                      let res = response.data;
                      if(res.status == 1){
                          if(res.data.length > 0){
                              for(var i =0;i<res.data.length; i++){
                                  for(var j = 0;j<res.data[i].coupon_list.length;j++){
                                      res.data[i].coupon_list[j].isActive = false;
                                  }
                              }
                              that.store_list = that.store_list.concat(res.data);
                              that.store_data = res.store_data;
                              that.store_coupon = res.store_coupon;
                          }else{

                          }

                      }else{
                          console.log("没有更多数据!");
                      }
                })
                .catch(function (error) {
                    console.log(error);
            });
        },
        //领取优惠券
        receiveCoupon:function(coupon_id,store_id){
            let that = this;
            let url = "/fang/store/user_coupon";
            let _token01 = that.$cookies.get("_token01");
            //后端返回_user_mark，存在证明没有注册手机号码
            let _user_mark = that.$store.state._user_mark;
            if(_user_mark){
                let content = "需要注册才能领取,去注册";
                that.createDialog(content);
            }else{
                const toast = that.$createToast({
                    time: 5000,
                    txt: ''
                  })
                  toast.show()
                that.$axios.post(url,this.$qs.stringify({
                    coupon_id:coupon_id,
                    access_token:that.$store.state._token01,
                })).then(function(response){
                     toast.hide();
                    let res = response.data;
                    if(res.status == 1){
                        let content = "领取成功，是否立即去使用";
                        that.showBtn(content,store_id,that);
                        that.coupon_isactive(store_id,coupon_id);
                    }
                    else if (res.status == -1) {
                        that.noLogin();
                    }else{
                        let content = res.msg;
                        that.showToastTxtOnly(content);
                    }
                })
                .catch(function(error){
                    toast.hide();
                });
            }
        },
        coupon_isactive(store_id,coupon_id){
            var id = this.store_list.findIndex(function (x) {
                return x.id === store_id
            })
            var couponid = this.store_list[id].coupon_list.findIndex(function (x) {
                return x.id === coupon_id
            })
            this.store_list[id].coupon_list[couponid].isActive = true;
        },
        createDialog(content){
            this.$createDialog({
               type: 'confirm',
               icon: 'cubeic-alert',
               title: '提示信息',
               content: content,
               confirmBtn: {
                 text: '确定',
                 active: true,
                 disabled: false,
                 href: 'javascript:;'
               },
               cancelBtn: {
                 text: '取消',
                 active: false,
                 disabled: false,
                 href: 'javascript:;'
               },
               onConfirm: () => {
                   this.binzeronefun()
               },
               onCancel: () => {

               }
             }).show()
        },
        binzeronefun:function(){
            this.$router.push("/binzerone");
        },
        //使用优惠券
        useCoupon:function(store_id){
            let url = '';
            if(/Alipay/.test(window.navigator.userAgent)) {
                url = this.$store.state.host+'/fang/scanpay/ali?store_id='+store_id;
                window.location.href = url;
            }
            else if (/MicroMessenger/.test(window.navigator.userAgent)) {
                url = this.$store.state.host+'/fang/scanpay/wechat?store_id='+store_id;
                window.location.href = url;
            } else {
                this.showAlert('请使用微信或支付宝支付');
            }

        },
        showBtn(content,store_id,that) {
             this.$createDialog({
               type: 'confirm',
               icon: 'cubeic-alert',
               title: '提示信息',
               content: content,
               confirmBtn: {
                 text: '立即使用',
                 active: true,
                 disabled: false,
                 href: 'javascript:;'
               },
               cancelBtn: {
                 text: '我再看看',
                 active: false,
                 disabled: false,
                 href: 'javascript:;'
               },
               onConfirm: () => {
                 that.useCoupon(store_id);
               },
               onCancel: () => {
               }
             }).show()
         },
         showToastTxtOnly(text) {
          this.toast = this.$createToast({
            txt: text,
            type: 'txt'
          })
          this.toast.show()
        },
         get_wexin_lat(){
             let that = this;
             const toast = that.$createToast({
                 time: 1000,
                 txt: ''
              })
              toast.show()
             wx.getLocation({
                  type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                  success: function (res) {
                     console.log(res,"res");
                      var latitude = parseFloat(res.latitude); // 纬度，浮点数，范围为90 ~ -90
                      var longitude = parseFloat(res.longitude); // 经度，浮点数，范围为180 ~ -180。
                      var speed = res.speed; // 速度，以米/每秒计
                      var accuracy = res.accuracy; // 位置精度
                      // wgs84 转百度
                      let bd09 = that.$options.methods.wgs84togcj02tobd09(longitude,latitude)
                      // that.serach_address_location(bd09.lat,bd09.lng)
                      return {lat:bd09.lat,lng:bd09.lng};
                  },
                  fail: function(res){
                      console.log(res,"fail");
                      setTimeout(function(){
                          const toastlog = that.$createToast({
                              time: 2000,
                            txt: "定位失败了,打开GPS定位试试",
                            type: 'txt'
                          })
                          toastlog.show()
                      },500)
                      return {};
                  },
                  complete:function(res){
                       toast.hide();
                  },
                  cancel: function (res) {
                       // alert('用户拒绝授权获取地理位置');
                       // that.serach_address_location(that.$store.state.latitude,that.$store.state.longitude);
                   }
             });
         },
         /**
         * WGS84转GCj02
         * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
         */
        wgs84togcj02tobd09 (lng, lat) {
              const xPI = 3.14159265358979324 * 3000.0 / 180.0
              const PI = 3.1415926535897932384626
              const a = 6378245.0
              const ee = 0.00669342162296594323
              // WGS84转GCj02
              let dlat = this.transformlat(lng - 105.0, lat - 35.0)
              let dlng = this.transformlng(lng - 105.0, lat - 35.0)
              let radlat = lat / 180.0 * PI
              let magic = Math.sin(radlat)
              magic = 1 - ee * magic * magic
              let sqrtmagic = Math.sqrt(magic)
              dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI)
              dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI)
              let mglat = lat + dlat
              let mglng = lng + dlng
              // 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
              let z = Math.sqrt(mglng * mglng + mglat * mglat) + 0.00002 * Math.sin(mglat * xPI)
              let theta = Math.atan2(mglat, mglng) + 0.000003 * Math.cos(mglng * xPI)
              let bdlng = z * Math.cos(theta) + 0.0065
              let bdlat = z * Math.sin(theta) + 0.006
              // return [bdlng, bdlat]
              return {lng: bdlng, lat: bdlat}
            },
            transformlat (lng, lat) {
              const PI = 3.1415926535897932384626
              let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng))
              ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0
              ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0
              ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0
              return ret
            },
            transformlng (lng, lat) {
              const PI = 3.1415926535897932384626
              let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng))
              ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0
              ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0
              ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0
              return ret
          }

    },
    components:{
    },
    computed: {
    },
    mounted:function(){


    },
    created() {

     },
    beforeCreate:function(){

    },
    activated:function(){
        //使用keep-alive以后进入页面只会触发activate
        let ln = this.get_wexin_lat();
        if(ln){
            this.get_store_list(ln.lat,bd09.ln);
        }else{
            this.get_store_list();
        }

    },
    beforeDestroy: function() {

    },
    deactivated:function(){

    },
    destroyed:function(){
        this.$router.back(); // 将添加记录从history中移除
    }
}
</script>
<style scoped>
.top> p{
    margin-top: 0.84rem;
    font-size: 0.48rem;
    color: #A6A6A6;
    font-weight: 500;
}
.top> h3{
    margin-top: 0.2rem;
    font-size: 0.64rem;
    color: #333333;
    font-weight: 500;
}
.top .shop_img{
    width: 2.88rem;
    height: 2.88rem;
    border-radius: 50%;
    margin: .5rem auto;
    overflow: hidden;
    background: #FFFFFF;
}
.top .shop_img img{
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.wrapper{
    margin: 0.8rem 1.28rem 0 1.28rem;
}
.wrapper .item{
    width: 100%;
    height: 4.16rem;
    border-radius: .15rem;
    background: #ffffff;
    margin: .6rem 0;
    display: flex;
    box-shadow: 0 0.4rem 0.5rem -0.3rem rgba(243,243,243,1);
    overflow: hidden;
}
.wrapper .item .lst_left{
    flex: 1;
    display: flex;
    align-items: center;
    text-align: left;
    position: relative;
}
.wrapper .item .lst_left::after {
    content: "";
    display: block;
    width: .9rem;
    height: .9rem;
    border-radius: 50%;
    background: #f8f8f8;
    position: absolute;
    right: -.5rem;
    top: -.45rem;
}
.wrapper .item .lst_left::before {
    content: "";
    display: block;
    width: .9rem;
    height: .9rem;
    border-radius: 50%;
    background: #f8f8f8;
    position: absolute;
    right: -.5rem;
    bottom: -.45rem;
}
.wrapper .item .lst_right{
    width: 4.32rem;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
}
.wrapper .item .lst_right .xiantiao_icon{
    width: .04rem;
    height: 2.84rem;
    position: absolute;
    left: 0;
}
.wrapper .item .lst_right::after {
    content: "";
    display: block;
    width: 0.04rem;
    height: 2.8rem;
    position: absolute;
    left: 0;
    top: 50%;
    -webkit-transform: translate(0,-50%);
    transform: translate(0,-50%);
    /* background: url(../images/coupon-xuxian@2.png) no-repeat;
    background-size: cover; */
}
.wrapper .item .lst_left .coupon_name{
    font-size: .64rem;
    color: #272727;
    font-weight: 600;
    margin-bottom: .4rem;
}
.wrapper .item .lst_left .coupon_info{
    color: #1ABBA2;
    font-size: .52rem;
    margin-bottom: .4rem;
}
.wrapper .item .lst_left .coupon_info > em{
    margin-left: .24rem;
}
.wrapper .item .lst_left .coupon_date{
    color: #B6B6B6;
    font-size: .52rem;
}
.wrapper .item .lst_right .coupon_price{
    font-size: .8rem;
    font-weight: bold;
    color: #272727;
    margin-bottom: .24rem;
}
.wrapper .item .lst_right .coupon_price > em{
    font-size: .58rem;
    color: #181818;
}
.wrapper .item .lst_right .coupon_btn{
    font-size: .44rem;
    color: #FFFFFF;
    display: block;
    width: 2.88rem;
    height: 1.16rem;
    line-height: 1.12rem;
    /* background: url('../images/page3_btn_coupon@2x.png') no-repeat;
    background-size: cover; */
}
.shop_list_box{
    margin: 0 0 0 1.2rem;
    padding: .52rem .2rem .52rem 0;
    background: #ffffff;
}
.border-bottom-1px::after{
    border-bottom-color: #FFD6D6D6;
}
.shop_list_box .shop_list_item{
        display: flex;
}
.shop_list_box .shop_list_item > .left_fl{
    width: 4.46rem;
    height: 4.16rem;
    flex: none;
    background: #f5f5f5;
}
.shop_list_box .shop_list_item > .left_fl img{
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.shop_list_box .shop_list_item > .right_fl{
    flex: 1;
    display: flex;
    padding-left: .64rem;
    overflow: hidden;
}
.shop_list_box .shop_list_item > .right_fl .right_info{
    overflow: hidden;
    width: 100%;
}
.shop_list_box .shop_list_item > .right_fl .right_info_top{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: flex-end;
}
.shop_list_box .shop_list_item > .right_fl .right_info_top .shop_name{
    font-size:.64rem;
    font-weight:600;
    color:rgba(4,4,4,1);
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
    margin-top: .18rem;
    text-align: left;
}
.shop_list_box .shop_list_item > .right_fl .right_info_top>span{
    font-size:.44rem;
    font-weight:500;
    color:rgba(124,124,124,1);
}
.shop_list_box .shop_list_item > .right_fl .shop_info{
    font-size:.44rem;
    font-weight:500;
    color:rgba(124,124,124,1);
    text-align: left;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    margin-top: .38rem;
}
.shop_list_box .shop_list_item > .right_fl .coupon_list{
    text-align: left;
    margin-top: .44rem;
        overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_list_bg{
    width: 5.48rem;
    height: .88rem;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 0 0 0.4rem;
    box-sizing: border-box;
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_list_bg p{
    overflow: hidden;
    /* text-overflow: ellipsis;
    white-space: nowrap; */
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_list_bg .coupon_icon{
    display: inline-block;
    width: .44rem;
    height: .44rem;
    vertical-align: middle;
    margin-right: .16rem;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_list_left{
    float: left;
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_list_right{
    width: 2.3rem;
    height: .88rem;
    float: left;
    font-size:.44rem;
    font-weight:600;
    color:rgba(255,255,255,1);
    text-align: center;
    line-height: 1rem;
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_none{
    background:linear-gradient(153deg,rgba(255,196,56,1),rgba(255,208,95,1));
}
.shop_list_box .shop_list_item > .right_fl .coupon_list .coupon_action{
    background:rgba(236,236,236,1);
}
.shop_list_box .shop_list_item > .right_fl .coupon_list  .received{
    background:rgb(246, 246, 246);
}
.shop_list_box .shop_list_item > .right_fl .coupon_txt{
    font-size:.4rem;
    font-weight:500;
    color:rgba(124,124,124,1);
}
</style>
